<template>
  <a-modal :width="1200" body-style="padding: 10px 20px" v-model:visible="showEditDialog" :title="currentItem.id ? '编辑采购单' : '创建采购单'" top="8vh" title-align="start" :mask-closable="false" @cancel="closedDialog">
    <a-form ref="formRef" :model="formInfo" :rules="rules">
      <a-row>
        <a-col :span="10">
          <a-form-item field="warehouse.warehouseCode" label="收货仓：" label-col-flex="100px">
            <a-select v-model="formInfo.warehouse" value-key="warehouseCode" allow-search placeholder="">
              <a-option v-for="(item, i) in warehouseList" :key="i" :value="item" :label="item.warehouseName" />
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="7">
          <a-form-item field="supplier.supplierCode" label="供应商：" label-col-flex="100px">
            <a-select v-model="formInfo.supplier" value-key="supplierCode" allow-search placeholder="">
              <a-option v-for="(item, i) in supplierList" :key="i" :value="item" :label="item.supplierName" />
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="7">
          <a-form-item field="user.id" label="需求人：" label-col-flex="100px">
            <a-select v-model="formInfo.user" value-key="id" placeholder="" allow-search>
              <a-option v-for="(item, i) in userList" :key="i" :value="item" :label="item.userName" />
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="10">
          <a-form-item field="settleType" label="结算方式：" label-col-flex="100px">
            <a-select v-model="formInfo.settleType" placeholder="">
              <a-option v-for="(item, i) in settleAccounts" :key="i" :value="item.val">{{ item.label }}</a-option>
            </a-select>
            <a-popover>
              <template #content>
                <div style="width: 400px">
                  <p>现款：是指采购订单下到供应商，供应商必须收到货款才会发货，这种模式采购订单确认即可进入到请款池，去请款支付，所以这种模式需要在订单确认之前确定好采购金额，交货时不允许调整采购金额。（这种方式必须填写产品单价）</p>
                  <p>现货：是指一手交钱一手交货，交一单货即可请一单款，这种模式可以在交货单上确认最终的采购金额。</p>
                  <p>月结：按自然月结款，这种模式每个月初会自动根据上月已完成的交货单，生成请款单。</p>
                </div>
              </template>
              <icon-question-circle style="margin-left: 5px" />
            </a-popover>
          </a-form-item>
        </a-col>
        <a-col :span="7">
          <a-form-item field="purchaseUser.id" label="采购员：" label-col-flex="100px">
            <a-select v-model="formInfo.purchaseUser" value-key="id" placeholder="" allow-search>
              <a-option v-for="(item, i) in userList" :key="i" :value="item" :label="item.userName" />
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="7">
          <a-form-item field="gmtExpectDelivery" label="期望交期：" label-col-flex="100px">
            <a-date-picker v-model="formInfo.gmtExpectDelivery" style="width: 100%" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="10">
          <a-form-item label="附件：" label-col-flex="100px">
            <div class="flex-wrap">
              <a-tag style="margin-right: 10px; margin-bottom: 10px" v-if="formInfo.attachment" color="arcoblue" @close="formInfo.attachment = ''" closable>
                {{ formInfo.attachment }}
              </a-tag>
              <a-upload action="/" :custom-request="uplaodFile" :show-file-list="false">
                <template #upload-button>
                  <a-button size="mini">
                    <template #icon>
                      <icon-upload />
                    </template>
                    <template #default>上传附件</template>
                  </a-button>
                </template>
              </a-upload>
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="14">
          <a-form-item label="备注：" label-col-flex="100px">
            <a-textarea v-model="formInfo.remark" placeholder="" allow-clear />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <a-space style="margin-bottom: 10px">
      <a-input-group>
        <a-input size="small" :style="{ width: '260px' }" v-model="searchVal" placeholder="请输入SKU" allow-clear>
          <template #suffix>
            <a-popover position="br" trigger="click" v-model:popup-visible="showPopover" @click="mulValue = searchVal ? searchVal.replace(/,/g, '\n') : ''">
              <icon-more-vertical style="cursor: pointer; margin-left: 5px" />
              <template #content>
                <a-textarea placeholder="请输入，一行一个" v-model="mulValue" :style="{ width: '200px', height: '200px' }" />
                <div class="footer flex-c-sb">
                  <a-button class="gray-outline" size="mini" @click="mulValue = ''">清空</a-button>
                  <div>
                    <a-button size="mini" class="gray-outline" @click="showPopover = false">取消</a-button>
                    <a-button type="outline" size="mini" style="margin-left: 5px" @click="addBatch">确认</a-button>
                  </div>
                </div>
              </template>
            </a-popover>
          </template>
        </a-input>
        <a-button type="primary" size="small" @click="getProductList">添加</a-button>
      </a-input-group>
      <a-button type="primary" size="small" @click="showChooseProductDialog = true">批量选择产品</a-button>
    </a-space>
    <a-table
      class="table-two-line show-border-table"
      ref="tableRef"
      row-key="id"
      :data="purchaseItems"
      :scroll="{
        x: '100%',
        y: 'calc(84vh - 340px)',
      }"
      size="mini"
      :bordered="{ cell: true }"
      :pagination="false"
    >
      <template #columns>
        <a-table-column data-index="img" title="图片" :width="60" fixed="left">
          <template #cell="{ record }">
            <ImgPopover :src="record.productImg">
              <template #con>
                <a-image width="40" height="40" fit="contain" :src="record.productImg" />
              </template>
            </ImgPopover>
          </template>
        </a-table-column>
        <a-table-column data-index="sku" title="SKU" :width="120" fixed="left">
          <template #cell="{ record }">
            <ShowSpuDetailBySku :val="record.sku" :showLimit="false" />
          </template>
        </a-table-column>
        <a-table-column data-index="productSpecs" title="SKU规格" :width="100">
          <template #cell="{ record }">
            <TextLimit :val="getProductSpecs(record)" />
          </template>
        </a-table-column>
        <a-table-column data-index="prop" :width="400">
          <template #title>
            <span>采购参数</span>
            <a-popover content="采购参数默认获取产品属性值，参数项目根据采购场景的属性模版配置而来。">
              <icon-question-circle />
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">
            <div class="purchase-props-w">
              <ul class="purchase-props">
                <li v-for="(prop, key) in record.purchaseSpecs" :key="key" :style="`width:${prop.type == 7 || prop.type == 8 ? '100' : '50'}%`">
                  <a-select size="mini" style="width: 100%" v-if="prop.code == 'X-chain'" v-model="prop.purchaseValue" @search="getChainList" :filter-option="false" :trigger-props="{ autoFitPopupMinWidth: true }" allow-search allow-clear :placeholder="prop.name" @change="changeProp(prop, rowIndex)">
                    <a-option v-for="(propVal, j) in chainList" :key="j" :value="propVal.skuName" :label="propVal.skuName" />
                  </a-select>
                  <a-select size="mini" style="width: 100%" v-else-if="prop.type == 1" v-model="prop.purchaseValue" :trigger-props="{ autoFitPopupMinWidth: true }" allow-search allow-clear :placeholder="prop.name" @change="changeProp(prop, rowIndex)">
                    <a-option v-for="(propVal, j) in getPropValueList(prop.code)" :key="j" :value="propVal.propValue" :label="propVal.propValue" />
                  </a-select>
                  <a-select size="mini" style="width: 100%" v-else-if="prop.type == 2" multiple :max-tag-count="1" v-model="prop.purchaseValue" :trigger-props="{ autoFitPopupMinWidth: true }" allow-search allow-clear :placeholder="prop.name" @change="changeProp(prop, rowIndex)">
                    <a-option v-for="(propVal, j) in getPropValueList(prop.code)" :key="j" :value="propVal.propValue" :label="propVal.propValue" />
                  </a-select>
                  <a-select size="mini" style="width: 100%" v-else-if="prop.type == 3" v-model="prop.purchaseValue" :trigger-props="{ autoFitPopupMinWidth: true }" allow-search allow-clear :placeholder="prop.name" @change="changeProp(prop, rowIndex)">
                    <a-option value="true" label="是" />
                    <a-option value="false" label="否" />
                  </a-select>
                  <a-input size="mini" v-else-if="prop.type == 4" v-model="prop.purchaseValue" allow-clear :placeholder="prop.name" />
                  <a-input-number size="mini" v-else-if="prop.type == 5 || prop.type == 6" v-model="prop.purchaseValue" allow-clear :placeholder="prop.name" :min="0" hide-button>
                    <template #suffix>
                      {{ prop.unit }}
                    </template>
                  </a-input-number>
                  <div v-else-if="prop.type == 7">
                    <a-input size="mini" v-model="prop.purchaseValue[0]" style="width: 33.33%" allow-clear :placeholder="prop.name" hide-button>
                      <template #suffix>
                        {{ prop.unit }}
                      </template>
                    </a-input>
                    <a-input size="mini" v-model="prop.purchaseValue[1]" style="width: 33.33%" allow-clear :placeholder="prop.name" hide-button>
                      <template #suffix>
                        {{ prop.unit }}
                      </template>
                    </a-input>
                    <a-input size="mini" v-model="prop.purchaseValue[2]" style="width: 33.33%" allow-clear :placeholder="prop.name" hide-button>
                      <template #suffix>
                        {{ prop.unit }}
                      </template>
                    </a-input>
                  </div>
                  <div v-else-if="prop.type == 8">
                    <a-input size="mini" v-model="prop.purchaseValue[0]" style="width: 50%" :placeholder="prop.name" allow-clear hide-button>
                      <template #suffix>
                        {{ prop.unit }}
                      </template>
                    </a-input>
                    <a-input size="mini" v-model="prop.purchaseValue[1]" style="width: 50%" :placeholder="prop.name" allow-clear hide-button>
                      <template #suffix>
                        {{ prop.unit }}
                      </template>
                    </a-input>
                  </div>
                </li>
              </ul>
              <div>
                <icon-double-down v-if="rowIndex != purchaseItems.length - 1" class="edit-icon" @click="setGlobalPurchaseSpecs(record, rowIndex)" />
                <a-popover position="bottom" trigger="click">
                  <template #content>
                    <p class="props-title">采购参数属性配置</p>
                    <a-scrollbar style="height: 300px; overflow: auto">
                      <ul class="props-list">
                        <li class="flex-c-sb" v-for="(item, i) in allProps" :key="i" @click="chooseProp(item, record, rowIndex)">
                          <span>{{ item.name }}</span>
                          <span v-if="record.purchaseSpecs && record.purchaseSpecs[item.code]"><icon-eye /></span>
                          <span v-else><icon-eye-invisible /></span>
                        </li>
                      </ul>
                    </a-scrollbar>
                  </template>
                  <p><icon-down-circle class="edit-icon" /></p>
                </a-popover>
              </div>
            </div>
          </template>
        </a-table-column>
        <a-table-column data-index="remark" title="备注" :width="140">
          <template #cell="{ record, rowIndex }">
            <div class="cell flex-c" style="width: 132px">
              <a-input v-model="record.remark" style="width: 90px" placeholder="" />
              <icon-double-down v-if="rowIndex != purchaseItems.length - 1" class="edit-icon" @click="setGlobal(record, 'remark', rowIndex)" />
            </div>
          </template>
        </a-table-column>
        <a-table-column data-index="num" title="采购数量" :width="100">
          <template #title>
            <span class="warningColor">*</span>
            <span>采购数量</span>
          </template>
          <template #cell="{ record, rowIndex }">
            <div class="cell flex-c">
              <a-input-number :precision="0" :min="0" v-model="record.purchaseAmt" style="width: 60px" placeholder="" hide-button />
              <icon-double-down v-if="rowIndex != purchaseItems.length - 1" class="edit-icon" @click="setGlobal(record, 'purchaseAmt', rowIndex)" />
            </div>
          </template>
        </a-table-column>
        <a-table-column data-index="materialPrice" title="材质单价(元/g)" :width="120">
          <template #title>
            <span>材质单价(元/g)</span>
            <a-popover>
              <template #content>
                <p style="width: 400px">材质单价，是指采购参数材质属性对应的材质价格，根据采购参数上的属性取当日最新的材质报价。</p>
              </template>
              <icon-question-circle />
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">
            <div class="cell flex-c">
              <a-input-number :precision="2" :min="0" v-model="record.materialPrice" style="width: 70px" placeholder="" hide-button />
              <icon-double-down v-if="rowIndex != purchaseItems.length - 1" class="edit-icon" @click="setGlobal(record, 'materialPrice', rowIndex)" />
            </div>
          </template>
        </a-table-column>

        <a-table-column data-index="productPrice" title="产品单价" :width="100">
          <template #title>
            <span>产品单价</span>
            <a-popover>
              <template #content>
                <p style="width: 400px">产品单价：单个产品的成本价，默认值从供应商报价获取，如果没有报价则从最近一次采购订单上获取。</p>
              </template>
              <icon-question-circle />
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">
            <div class="cell flex-c">
              <a-input-number :precision="2" :min="0" v-model="record.productPrice" style="width: 60px" placeholder="" hide-button />
              <icon-double-down v-if="rowIndex != purchaseItems.length - 1" class="edit-icon" @click="setGlobal(record, 'productPrice', rowIndex)" />
            </div>
          </template>
        </a-table-column>
        <a-table-column data-index="laborPrice" title="工费单价" :width="100">
          <template #title>
            <span>工费单价</span>
            <a-popover>
              <template #content>
                <p style="width: 400px">工费：这里的工费单价是指供应商报价的组成部分，有些供应商的报价是不含工费的或者工费是包含在产品单价的，则可以不填写。</p>
              </template>
              <icon-question-circle />
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">
            <div class="cell flex-c">
              <a-input-number :precision="2" :min="0" v-model="record.laborPrice" style="width: 60px" placeholder="" hide-button />
              <icon-double-down v-if="rowIndex != purchaseItems.length - 1" class="edit-icon" @click="setGlobal(record, 'laborPrice', rowIndex)" />
            </div>
          </template>
        </a-table-column>
        <a-table-column title="税率" :width="180">
          <template #cell="{ record, rowIndex }">
            <div class="cell flex-c">
              <a-select v-model="record.priceType" size="medium" style="width: 70px">
                <a-option :value="0">不含税</a-option>
                <a-option :value="1">含税</a-option>
              </a-select>
              <a-input-number v-model="record.rate" style="width: 60px" hide-button placeholder="" />
              <span>%</span>
              <icon-double-down v-if="rowIndex != purchaseItems.length - 1" class="edit-icon" @click="setGlobalRate(record, rowIndex)" />
            </div>
          </template>
        </a-table-column>
        <a-table-column title="是否加急" :width="100">
          <template #cell="{ rowIndex, record }">
            <a-space>
              <a-switch v-model="record.urgent" checked-text="开" unchecked-text="关" />
              <icon-double-down v-if="rowIndex != purchaseItems.length - 1" class="edit-icon" @click="setGlobal(record, 'urgent', rowIndex)" />
            </a-space>
          </template>
        </a-table-column>
        <a-table-column title="操作" :width="60" fixed="right">
          <template #cell="{ rowIndex }">
            <a-popconfirm v-if="purchaseItems.length > 1" content="确定是否移除?" @ok="purchaseItems.splice(rowIndex, 1)" type="error">
              <a-button type="text">移除</a-button>
            </a-popconfirm>
          </template>
        </a-table-column>
      </template>
    </a-table>
    <template #footer>
      <a-space>
        <a-button size="small" class="gray-outline" @click="closedDialog">取消</a-button>
        <a-button size="small" v-if="$authPass('procurement.purchase.submit')" type="primary" @click="submitData(10)" :disabled="submitLoading">保存并提交审核</a-button>
        <a-button v-if="currentItem.status != 11 && currentItem.status != 21" size="small" type="primary" @click="submitData(1)" :disabled="submitLoading">保存草稿</a-button>
      </a-space>
    </template>
  </a-modal>
  <!-- 选择产品 -->
  <ChooseProduct v-if="showChooseProductDialog" title="添加采购产品" :needCount="false" :isShow="showChooseProductDialog" :multiple="true" @closed="showChooseProductDialog = false" @success="chooseProduct" />
</template>
<script lang="ts" setup>
  import { ref, onMounted, PropType } from 'vue'
  import useUserStore from '@/store/modules/user'
  import { upload } from '@/api/base'
  import { Message } from '@arco-design/web-vue'
  import { createPurchaseOrder, updatePurchaseOrder, findLatestPurchaseItemList } from '@/api/purchaseApplication'
  import { parseJson } from '@/utils'
  import ChooseProduct from '@/components/ChooseProduct.vue'
  import { cloneDeep } from 'lodash-es'
  import { findMaterialQuotePage } from '@/api/system'
  import { skuPageRelatedForCompanyVer, getRelatedList, pageFitting, getPropertyTemplateList } from '@/api/product'
  import useBaseDataStore from '@/store/modules/base-data'

  onMounted(() => {
    getAllProps()
    getPurchaseProps()
    getQuoteList()
    getChainList()
    getUserList()
    if (props.currentItem.id) {
      getOrderDetail()
    } else {
      setDefaultData()
    }
  })

  const useBaseData = useBaseDataStore()
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    companyList: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
    supplierList: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
    warehouseList: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
    currentItem: {
      type: Object,
      default: () => {},
    },
  })
  const settleAccounts = [
    {
      val: 1,
      label: '月结（按月交货完成结款）',
    },
    {
      val: 2,
      label: '现货（交货即可结款）',
    },
    {
      val: 3,
      label: '现款（先付款后发货）',
    },
  ]
  const rules = ref({
    'warehouse.warehouseCode': [{ required: true, message: '请选择收货仓库' }],
    'supplier.supplierCode': [{ required: true, message: '请选择供应商' }],
    'purchaseUser.id': [{ required: true, message: '请选择采购员' }],
    settleType: [{ required: true, message: '请选择结算方式' }],
    gmtExpectDelivery: [{ required: true, message: '请选择期望交期' }],
  })
  const userStore = useUserStore()
  const showEditDialog = ref(props.isShow)
  const formInfo = ref<any>({})
  const purchaseItems = ref<Array<any>>([])
  const submitLoading = ref(false)
  const showChooseProductDialog = ref(false)
  const formRef = ref()
  const searchVal = ref()
  const mulValue = ref()
  const showPopover = ref(false)
  const allProps = ref<Array<any>>([])
  const quoteList = ref<Array<any>>([])
  const userList = ref<Array<any>>([])
  let skuPropsMap: any = {}
  let purchasePropsMap: any = {}
  let allPropsMap: any = {}
  let quoteMap: any = {}
  const propDefaultValByType = {
    1: null,
    2: [],
    3: null,
    4: null,
    5: null,
    6: null,
    7: ['', '', ''],
    8: ['', ''],
  }
  const chainList = ref<Array<any>>([])
  const chainCatId = import.meta.env.VITE_CHAIN_CATEGORY_ID

  // 获取配链列表
  async function getChainList(val?: string) {
    const params: any = {
      keyword: val,
      keywordType: 'skuName',
      searchType: 'fuzzy',
      needCount: false,
      categoryId: chainCatId,
      pageNum: 1,
      pageSize: 50,
    }
    const res: any = await pageFitting(params)
    chainList.value = res?.data?.records || []
  }
  // 获取报价列表
  async function getQuoteList() {
    let params = {
      pageNum: 1,
      pageSize: 500,
      display: true,
    }
    const res: any = await findMaterialQuotePage(params)
    quoteList.value = res?.data?.records || []
    quoteList.value.forEach((el: any) => {
      quoteMap[el.productName] = el
    })
  }
  // 获取采购场景的属性模板  一个类目加采购场景为一条数据
  async function getPurchaseProps() {
    purchasePropsMap = {}
    const res = await getPropertyTemplateList({
      pageNum: 1,
      pageSize: 1000,
      scenes: 'purchase',
    })
    let _list = res?.data?.records || []
    _list.forEach((item: any) => {
      let propItems = item.itemList.map((propEl: any) => propEl.prop)
      item.categoryList.forEach((el: any) => {
        purchasePropsMap[el.productCatgoryId] = propItems
      })
    })
  }
  async function getUserList() {
    await useBaseData.getUserList()
    userList.value = useBaseData.userList || []
  }

  // 获取详情
  async function getOrderDetail() {
    let _detail = props.currentItem
    formInfo.value = {
      gmtExpectDelivery: _detail.gmtExpectDelivery,
      settleType: _detail.settleType,
      attachment: _detail.attachment,
      remark: _detail.remark,
      id: _detail.id,
      status: _detail.status,
    }
    console.log(_detail.warehouseCode)
    if (_detail.warehouseCode) {
      formInfo.value.warehouse = {
        warehouseCode: _detail.warehouseCode,
        warehouseName: _detail.warehouseName,
      }
    }
    if (_detail.supplierCode) {
      formInfo.value.supplier = {
        id: _detail.supplierId,
        supplierCode: _detail.supplierCode,
        supplierName: _detail.supplierName,
      }
    }
    if (_detail.salesmanId) {
      formInfo.value.user = {
        id: _detail.salesmanId,
        userName: _detail.salesmanName,
      }
    }
    if (_detail.purchaseUid) {
      formInfo.value.purchaseUser = {
        id: _detail.purchaseUid,
        userName: _detail.purchaseUname,
      }
    }
    purchaseItems.value = _detail.billItems.map((el: any) => {
      let _item = cloneDeep(el)
      _item.purchaseSpecs = parseJson(_item.purchaseSpecs, {}) || {}
      // 处理从erp过来的默认属性
      if (_item.orderFrom == 'erp') {
        Object.keys(_item.purchaseSpecs).forEach((key: string) => {
          let _prop = _item.purchaseSpecs[key]
          _prop.purchaseValue = _prop.purchaseValue ? parseJson(_prop.purchaseValue, _prop.purchaseValue) : propDefaultValByType[_prop.type]
        })
      }
      return _item
    })
  }
  // 获取所有的属性列表
  async function getAllProps() {
    const res = await getRelatedList({
      pageNum: 1,
      pageSize: 1000,
    })
    allProps.value = res?.data?.records || []
    allPropsMap = {}
    allProps.value.forEach((el: any) => {
      allPropsMap[el.code] = el
    })
  }
  // 属性属性值选择项
  function getPropValueList(code: string) {
    return allPropsMap[code]?.propValueList || []
  }

  // 点击增加或隐藏属性
  function chooseProp(prop: any, item: any, index: number) {
    item.purchaseSpecs = item.purchaseSpecs || {}
    if (item.purchaseSpecs?.[prop.code]) {
      delete item.purchaseSpecs[prop.code]
    } else {
      let purchaseValue = getAddPropVal(prop, item.sku)
      item.purchaseSpecs[prop.code] = {
        ...prop,
        purchaseValue: purchaseValue,
      }
      changeProp(item.purchaseSpecs[prop.code], index)
    }
  }
  function getAddPropVal(prop: any, sku: string) {
    let purchaseValue: any
    // 获取产品的属性值
    let productProp = skuPropsMap?.[sku]?.[prop.code] || {}
    switch (prop.type) {
      case 1:
        purchaseValue = productProp.valueStr || null
        break
      case 2:
        purchaseValue = productProp.valueStrList || []
        break
      case 3:
        purchaseValue = productProp.valueBoolean || null
        break
      case 4:
        purchaseValue = productProp.valueStr || null
        break
      case 5:
        purchaseValue = productProp.valueNumber || null
        break
      case 6:
        purchaseValue = productProp.valueBigDecimal || null
        break
      case 7:
        let strs = productProp.valueStrList || []
        purchaseValue = [strs[0] || '', strs[1] || '', strs[2] || '']
      case 8:
        let strs2 = productProp.valueStrList || []
        purchaseValue = [strs2[0] || '', strs2[1] || '']
        break
      default:
        break
    }
    return purchaseValue
  }
  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }

  // 添加初始化数据
  function setDefaultData() {
    let defaultUser = {
      id: userStore.userId,
      userName: userStore.userName,
    }
    formInfo.value.user = { ...defaultUser }
  }
  function addBatch() {
    searchVal.value = mulValue.value?.split('\n')?.join(',')
    showPopover.value = false
  }

  // 上传附件
  async function uplaodFile(options: any) {
    let { fileItem } = options
    let formData = new FormData()
    formData.append('file', fileItem.file)
    const res: any = await upload(formData)
    if (res?.data?.publicUrl) {
      formInfo.value.attachment = res.data.publicUrl
    }
  }
  //设置全局
  function setGlobal(item: any, key: string, rowIndex: number) {
    const newVal = item[key]
    purchaseItems.value.forEach((el: any, index: number) => {
      if (index > rowIndex) {
        el[key] = typeof newVal == 'object' ? cloneDeep(newVal) : newVal
      }
    })
  }
  //全局设置单件工工费
  function setGlobalRate(item: any, rowIndex: number) {
    setGlobal(item, 'rate', rowIndex)
    setGlobal(item, 'priceType', rowIndex)
  }
  // 添加产品的信息
  function setItemInfoByProduct(item: any) {
    let obj: any = {
      productId: item.id,
      productImg: item?.productPicList?.[0]?.url,
      productName: item.skuName,
      productSpecs: item.specValueList ? JSON.stringify(item.specValueList) : null,
      productRemark: item.remark,
      sku: item.sku,
      spu: item.spu,
      brandId: item?.brand?.id,
      brandName: item?.brand?.name,
      cateId: item.category?.id,
      cateName: item.category?.name,
      urgent: false,
      remark: item.remark,
      priceType: 1,
      purchaseSpecs: {},
    }
    // 有采购模板的默认采购模板
    let purchaseProps = purchasePropsMap[obj.cateId]
    if (purchaseProps?.length) {
      purchaseProps.forEach((prop: any) => {
        let purchaseValue = getAddPropVal(prop, obj.sku)
        obj.purchaseSpecs[prop.code] = {
          ...prop,
          purchaseValue: purchaseValue,
        }
      })
    }
    // 设置默认材质单价，取报价里相同材质的价格
    let material = Object.values(obj.purchaseSpecs)?.find((el: any) => el.name == '材质')?.purchaseValue
    if (material) {
      obj.materialPrice = quoteMap[material]?.quotePrice
    }
    return obj
  }
  // 单个切换材质
  function changeProp(prop: any, index: number) {
    // 切换了材质需要更换材质报价
    if (prop.name == '材质') {
      purchaseItems.value[index].materialPrice = quoteMap[prop.purchaseValue]?.quotePrice
    }
  }
  //设置属性全局
  function setGlobalPurchaseSpecs(item: any, rowIndex: number) {
    const newVal = item.purchaseSpecs
    purchaseItems.value.forEach((el: any, index: number) => {
      if (index > rowIndex) {
        el.purchaseSpecs = cloneDeep(newVal)
        //更新默认报价
        Object.values(el.purchaseSpecs).forEach((prop: any) => {
          if (prop.name == '材质') {
            changeProp(prop, index)
          }
        })
      }
    })
  }
  // 添加产品
  function chooseProduct(list: Array<any>) {
    // 不重复添加相同SKU
    let addList = list.filter((item: any) => !purchaseItems.value.some((el: any) => item.sku == el.sku))
    if (!addList?.length) return
    let skus: Array<string> = []
    addList.forEach((el: any) => {
      skus.push(el.sku)
      skuPropsMap[el.sku] = {}
      el.propList?.forEach((prop: any) => {
        skuPropsMap[el.sku][prop.code] = prop
      })
      purchaseItems.value.push(setItemInfoByProduct(el))
    })
    setDefaultProductPrice(skus)
  }
  // 批量设置产品单价
  async function setDefaultProductPrice(skus: Array<string>) {
    // 单个产品的成本价，默认值从供应商报价获取，如果没有报价则从最近一次采购订单上获取。
    // 当前供应商报价没有，所以直接取最近一次采购订单上的数据
    const res: any = await findLatestPurchaseItemList({ skus: skus.join(',') })
    let list = res?.data || []
    let orderItemMap: any = {}
    list.forEach((el: any) => {
      orderItemMap[el.sku] = el
    })
    purchaseItems.value.forEach((el: any) => {
      el.productPrice = orderItemMap[el.sku]?.productPrice
    })
  }
  // 输入sku直接添加产品
  async function getProductList() {
    if (!searchVal.value) return
    const res: any = await skuPageRelatedForCompanyVer({
      pageSize: 100,
      pageNum: 1,
      searchType: 'exact',
      keywordType: 'sku',
      keyword: searchVal.value,
    })
    let list = res?.data?.records || []
    chooseProduct(list)
  }

  // 关闭
  function closedDialog() {
    showEditDialog.value = false
    emit('closed')
  }

  // 校验
  async function validInfo() {
    let valid = await formRef.value.validate((valid: any) => {
      return valid
    })
    if (valid) return false
    if (!purchaseItems.value.length) {
      Message.error('请最少增加一个产品')
      return false
    }
    for (let el of purchaseItems.value) {
      if (!el.purchaseAmt) {
        Message.error('采购数量必填')
        return false
      }
    }
    return true
  }
  function saveItemData() {
    let list = JSON.parse(JSON.stringify(purchaseItems.value))
    list.forEach((el: any) => {
      el.purchaseSpecs = JSON.stringify(el.purchaseSpecs || {})
      el.gmtExpectDelivery = formInfo.value.gmtExpectDelivery
    })
    return list
  }
  // 保存信息
  async function submitData(status: number) {
    let valid = await validInfo()
    if (!valid) return false
    let formVal = cloneDeep(formInfo.value)
    formVal.salesmanId = formVal.user?.id
    formVal.salesmanName = formVal.user?.userName
    formVal.warehouseCode = formVal.warehouse?.warehouseCode
    formVal.warehouseName = formVal.warehouse?.warehouseName
    formVal.supplierId = formVal.supplier?.id
    formVal.supplierCode = formVal.supplier?.supplierCode
    formVal.supplierName = formVal.supplier?.supplierName
    formVal.purchaseUid = formVal.purchaseUser?.id
    formVal.purchaseUname = formVal.purchaseUser?.userName
    delete formVal.user
    delete formVal.warehouse
    delete formVal.purchaseUser
    delete formVal.supplier
    let params: any = {
      ...formVal,
      billItems: saveItemData(),
      status: status,
    }
    submitLoading.value = true
    let res: any
    if (!props.currentItem.id) {
      res = await createPurchaseOrder(params)
    } else {
      params.id = formInfo.value.id
      res = await updatePurchaseOrder(params)
    }
    submitLoading.value = false
    if (!res) return false
    Message.success('保存成功')
    emit('success')
    closedDialog()
  }
</script>
<style lang="less" scoped>
  .arco-form-item {
    margin-bottom: 10px;
  }

  .edit-icon {
    font-size: 16px;
    margin-left: 5px;
    cursor: pointer;
  }
  .price-type {
    font-size: 12px;
    transform: scale(0.82);
    position: relative;
    left: -4px;
  }
  .props-list {
    width: 200px;
    li {
      padding-right: 10px;
      margin-bottom: 5px;
    }
  }
  .props-title {
    margin-bottom: 5px;
  }
  .purchase-props {
    display: flex;
    flex-wrap: wrap;
    flex: 1;
    li {
      width: 50%;
      padding-right: 5px;
      margin-top: 5px;
    }
  }
  .purchase-props-w {
    display: flex;
    justify-content: space-between;
  }
  :deep(.arco-table-td) {
    .arco-table-cell {
      padding: 0 5px;
    }
    .arco-select-view-single {
      padding: 0 5px;
    }
    .arco-input-wrapper {
      padding: 0 5px;
    }
    .arco-select-view-value {
      font-size: 12px !important;
      min-height: 26px;
    }
    .arco-input {
      font-size: 12px !important;
    }
  }
</style>
